import apis from './modules';
import store from '../store';
import prenv from '../prenv';
import storage from '../commons/storage';
import { showLoading, hideLoading } from '../commons/loading';
import { getVersion, getPlatform, clone, getAppId, clearUserStorage } from '../commons/utils';
import { ERROR_MESSAGE_CODE, TOKEN_ERROR_CODE_OPTIONS, EMPTY_PAGE_PATH, CUSTOM_ERROR_CODE } from './const';
import { checkLoginToken } from '@/commons/utils';

/** http 请求计数器 */
let httpCounter = 0;

/** 是否存在toast */
let isToast = false;

/**
 * 开启Loading效果
 * @param {*} sld
 */
export const startShowLoading = sld => {
    if (httpCounter === 0 && sld && !isToast) {
        showLoading();
    }
};

/**
 * 关闭Loading效果
 */
const endShowLoading = () => {
    if (httpCounter > 0) {
        httpCounter--;
    }
    if (httpCounter === 0 && !isToast) {
        hideLoading();
    }
};

/**
 * 弹框提示
 * @param {*} title
 */
const toastHandler = title => {
    endShowLoading();
    isToast = true;
    uni.showToast({
        title,
        icon: 'none',
        duration: 2000
    });
    setTimeout(() => {
        isToast = false;
    }, 2000);
};

/**
 *  获取网关名称
 *  @param {请求名称} name
 */
const getApiAndgatewayName = name => {
    const api = apis.filter(v => {
        return v.name === name;
    });
    if (api.length === 0) {
        throw new Error(`未找到${name}对应的API服务地址`);
    } else {
        const retApi = clone(api[0]);
        const currentEnv = store.useEnvStore().currentEnv;
        let gatewayName = retApi.gatewayName;
        if (currentEnv === 'development' && retApi.mock) {
            gatewayName = 'mock';
        }
        return { retApi, gatewayName };
    }
};

/**
 * 获取请求信息
 * @param {请求名称} name
 */
export const getApi = name => {
    const { retApi, gatewayName } = getApiAndgatewayName(name);
    const currentEnv = store.useEnvStore().currentEnv;
    retApi.url = prenv[currentEnv]['API_BASE_URL'][gatewayName] + retApi.url;
    return retApi;
};

/**
 * 封装请求头部信息
 * @param {头部信息} header
 * @param {接口入参} data
 */
export const getHeader = function (name) {
    const { gatewayName } = getApiAndgatewayName(name);
    const ZW_TENANT_ID = storage.get('ZW_TENANT_ID') || '';
    const ZW_CORP_ID = storage.get('ZW_CORP_ID') || '';

    if (gatewayName === 'lbsgw') {
        const ZW_LBS_TOKEN = storage.get('ZW_LBS_TOKEN') || '';
        const ZW_LBS_CLIENT_ID = storage.get('ZW_LBS_CLIENT_ID') || '';
        const ZW_LBS_CLIENT_SECRET = storage.get('ZW_LBS_CLIENT_SECRET') || '';
        const target = {
            token: ZW_LBS_TOKEN,
            'client-id': ZW_LBS_CLIENT_ID,
            'client-secret': ZW_LBS_CLIENT_SECRET,
            'tenant-id': ZW_TENANT_ID,
            'corp-id': ZW_CORP_ID
        };
        return target;
    } else {
        const reqtime = Date.now();
        const terminal = uni.getSystemInfoSync().system.indexOf('iOS') > -1 ? 2 : 1;
        const token = storage.get('token') || '';
        const channel = storage.get('channel') || '';
        const ZW_SHOP_ID = storage.get('ZW_SHOP_ID') || '';
        const appVersion = getVersion();
        const platform = getPlatform();
        const appId = getAppId();
        const target = {
            appVersion,
            token,
            reqtime,
            platform,
            terminal,
            channel,
            'ZW-APP-ID': appId,
            'ZW-SHOP-ID': ZW_SHOP_ID,
            'ZW-TENANT-ID': ZW_TENANT_ID,
            'ZW-CORP-ID': ZW_CORP_ID
        };
        return target;
    }
};

/**
 * 请求成功处理函数
 * @param {*} req
 * @param {*} res
 * @param {*} resolve
 * @param {*} reject
 */
export const successHandler = async (req, res, resolve, reject) => {
    if (res.data.code === 0) {
        resolve(res.data);
        endShowLoading();
    } else if (TOKEN_ERROR_CODE_OPTIONS.includes(res.data.code)) {
        // token 失效重新登陆
        await checkLoginToken();
        endShowLoading();
    } else {
        errorHandler(req, res, reject);
    }
};

export const errorHandler = function (req, res, reject) {
    let title = '';
    if (res.statusCode === 200) {
        /**
         * 如果是501且pem为false 则拦截
         * 如果是501且pem为true 则放开
         * 如果不是501且pem为false 则拦截
         * 如果不是501且pem为true 则放开
         */
        if ([501].includes(res.data.code)) {
            if (!req.pem) {
                title = ERROR_MESSAGE_CODE[res.data.code];
            }
        } else {
            if (!req.pem) {
                title = res.data.msg;
            }
        }
    } else {
        if (res.statusCode === 429) {
            if (req.lmt === 0) {
                title = ERROR_MESSAGE_CODE[res.statusCode];
            } else if (req.lmt === -1) {
                return false;
            } else if (req.lmt === 2) {
                uni.navigateTo({ url: EMPTY_PAGE_PATH });
            }
        } else if (TOKEN_ERROR_CODE_OPTIONS.includes(res.data.code)) {
            const useRoute = store.useRouteStore();
            if (!useRoute.lockStatus) {
                uni.navigateTo({
                    url: '/pages-user/login/index'
                });
                useRoute.lockStatus = true;
            }
        } else if (CUSTOM_ERROR_CODE.includes(res.data.code)) {
            title = ERROR_MESSAGE_CODE[res.data.code];
        } else {
            title = ERROR_MESSAGE_CODE['other'];
            // 需要sentry来处理
        }
    }
    if (title) {
        toastHandler(title);
    } else {
        endShowLoading();
        reject(res);
    }
};

/**
 * 请求失败处理函数
 * @param {*} err
 */
export const failHandler = err => {
    const title = ERROR_MESSAGE_CODE['other'];
    toastHandler(title);
};
